package com.tjhk.netty.test;

import com.tjhk.netty.codec.MessageDecoder;
import com.tjhk.netty.serialize.SerializeUtil;
import com.tjhk.netty.test.model.MyHeader;
import com.tjhk.netty.test.model.MyMessage;
import com.tjhk.netty.util.ProtocolUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;
import java.time.LocalDateTime;

public class JTMessageDecoder implements MessageDecoder {
    private final Logger log = LoggerFactory.getLogger(JTMessageDecoder.class.getSimpleName());
    @Override
    public Object decode(ByteBuf byteBuf) {
        if (byteBuf.readableBytes() > 0){
            boolean verify  = ProtocolUtil.verifyBcc(byteBuf);
            if (!verify) {
                log.error("BCC校验错误！hex:[{}]",ByteBufUtil.hexDump(byteBuf));
                return null;
            }
            MyHeader myHeader = new MyHeader();
            String hex = ByteBufUtil.hexDump(byteBuf);
            System.out.println(hex);
            SerializeUtil.readFrom(byteBuf.slice(0, MyHeader.headerLength),myHeader);
            ByteBufUtil.hexDump(byteBuf);
            System.out.println(hex);
            MyMessage message = new MyMessage();
            ByteBuf bodyBuf = byteBuf.slice(MyHeader.headerLength,myHeader.getBodyLength());
            hex = ByteBufUtil.hexDump(bodyBuf);
            System.out.println(hex);
            SerializeUtil.readFrom(bodyBuf,message);
            message.setMessageId(myHeader.getMessageId());
            message.setBody("客户端你好！");
            System.out.println(message);
            return message;
        }else {
            return null;
        }
    }
}
